package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func helloHandler(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "Hello www.topgoer.com!",
	})
}

// 定义中间
func MiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		t := time.Now()
		fmt.Println("中间件开始执行了")
		// 设置变量到Context的key中，可以通过Get()取
		c.Set("request", "中间件")
		status := c.Writer.Status()
		fmt.Println("中间件执行完毕", status)
		t2 := time.Since(t)
		fmt.Println("time:", t2)
	}
}


func main() {
	r := gin.Default()

	// 注册中间件
	r.Use(MiddleWare())

	r.LoadHTMLGlob("template/**/*")

	r.Static("/static", "./static")
	r.StaticFS("/more_static", http.Dir("my_file_system"))
	r.StaticFile("/favicon.ico", "/resources/favicon.ico")

	{

		r.GET("/", func(c *gin.Context) {
			c.HTML(http.StatusOK, "default/index.html", gin.H{"title": "李清波 - 人生本来就是一种修行", "address": "www.5lmh.com"})
		})

		r.GET("/index", func(c *gin.Context) {
			c.HTML(http.StatusOK, "user/index.html", gin.H{"title": "我是测试", "address": "www.5lmh.com"})
		})

		r.GET("/test", helloHandler)
		if err := r.Run(); err != nil {
			fmt.Println("startup service failed, err:%v\n", err)
		}

	}

	r.Run()
}